package com.mulanweb.api.module.controller;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.mulanweb.api.module.model.AdminUser;
import com.mulanweb.api.module.model.Seller;
import com.mulanweb.db.common.Constant;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;

import java.io.IOException;

/**
 * Created by Administrator on 2016/10/25.
 */

@ValidateFile
public class LoginController extends BaseController {

    @ValidateForm
    public void login(){
        String username = getPara("username");
        String password = getPara("password");
        if(username !=null && password != null){
            AdminUser adminUser = AdminUser.dao.findFirst("SELECT * FROM admin_user WHERE username=? AND password=? AND delete_time IS NULL",username, HashKit.md5("mulan_xxl&admin_login"+password));
            if(StrKit.notNull(adminUser)){
                adminUser.setPassword("");
                super.setSessionAttr(Constant.XinXiLan.ADMIN_LOGIN_TAG, "yes");
                super.setSessionAttr("adminId",adminUser.getId());
                super.redirect("/admin-view/main/main.jsp");
            }else{
                super.redirect(Constant.XinXiLan.ADMIN_LOGIN_URL_ERROR);
            }
        }else{
            super.redirect(Constant.XinXiLan.ADMIN_LOGIN_URL_ERROR);
        }
    }

    @ValidateForm
    public void sellerLogin()throws IOException{
        String username = getPara("username");
        String password = getPara("password");
        Integer loginType = getParaToInt("loginType");
        if(username !=null && password != null){
            Seller seller= Seller.dao.findFirst("SELECT * FROM seller WHERE username=? AND password=? AND delete_time IS NULL",username, HashKit.md5("mulan_xxl&seller_login"+password));
            if(StrKit.notNull(seller)){
                seller.setPassword("");
                super.setSessionAttr(Constant.XinXiLan.SELLER_LOGIN_TAG, "yes");
                super.setSessionAttr("sellerId",seller.getId());
                if(loginType == 1){
                    super.setSessionAttr("sellerName",seller.getSellerName());
                    super.setSessionAttr("sellerId",seller.getId());
                    super.redirect("/seller-view/pc-view/index.jsp?id="+seller.getId());
                }else{
                    super.redirect("/seller-view/mobile-view/index.jsp");
                }
            }else{
                super.redirect(Constant.XinXiLan.SELLER_LOGIN_URL_ERROR);
            }
        }else{
            super.redirect(Constant.XinXiLan.SELLER_LOGIN_URL_ERROR);
        }
    }

    public void sellerLogout(){
        super.removeSessionAttr(Constant.XinXiLan.SELLER_LOGIN_TAG);
        super.redirect("/common/login/seller_login.jsp");
    }
}
